// service/common/query_list.go
package common

import (
	"fmt"
	"gorm.io/gorm"
	"muziai-server/global"
	"muziai-server/models"
)

type Option struct {
	Page     models.Page
	Likes    []string
	Debug    bool
	Preloads []string
	Where    *gorm.DB
	Sort     string
	Unscoped bool //是否查询删除的
}

func QueryList[T any](model T, option Option) (list []T, count int64, err error) {

	// 精确匹配
	db := global.DB.Where(model)
	query := global.DB.Where("")
	// 开启日志
	if option.Unscoped {
		db = db.Unscoped()
	}
	// 开启日志
	if option.Debug {
		db = db.Debug()
	}
	//排序
	if option.Sort != "" {
		db = db.Order(option.Sort)

	}

	// 高级查询
	if option.Where != nil {
		db = db.Where(option.Where)
	}

	// 模糊匹配
	if option.Page.Key != "" {
		like := global.DB.Where("")
		for _, column := range option.Likes {
			// column like ?
			like.Or(fmt.Sprintf("%s like ?", column), fmt.Sprintf("%%%s%%", option.Page.Key))
		}
		query.Where(like)
	}
	db.Where(query).Model(model).Count(&count)

	// 预加载
	for _, preload := range option.Preloads {
		db = db.Preload(preload)
	}

	// 分页的
	if option.Page.Limit <= 0 {
		option.Page.Limit = 10
	}
	if option.Page.Page < 1 {
		option.Page.Page = 1
	}
	offset := option.Page.Limit * (option.Page.Page - 1)
	db.Where(query).Offset(offset).Limit(option.Page.Limit).Find(&list)
	return
}
